/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.encrypters;

import static org.junit.Assert.*;

import java.nio.ByteBuffer;
import javax.crypto.SecretKey;

import org.junit.Test;
import org.latestbit.smartobjects.encrypters.StdSymmetricEncrypter;
import org.latestbit.smartobjects.io.ResizableByteBuffer;
import org.latestbit.smartobjects.utils.ByteTools;

public class StdSymmetricEncrypterTest {

	@Test
	public void testStdSymmetricEncrypter() throws Exception {
		
		ISymmetricDataEncrypter encrypter = new StdSymmetricEncrypter();
		SecretKey secretKey = encrypter.generateSecret();
		System.err.println("Key: "+ByteTools.byteArrayToHexString( secretKey.getEncoded() ));
		
		encrypter.initCipher(secretKey);
		
		ByteBuffer inputBuffer = ByteBuffer.allocate(10);
		inputBuffer.put(new byte[] { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E });
		inputBuffer.put(new byte[] { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E });
		inputBuffer.flip();
		ResizableByteBuffer output = new ResizableByteBuffer(false, 5024, 5024, 0);
		encrypter.encrypt( inputBuffer, output );
		
		output.getBuffer().flip();
		
		byte[] printArray = new byte[output.getBuffer().limit()];
		output.getBuffer().get(printArray);
		output.getBuffer().position(0);
		System.err.println("Encoded: "+ByteTools.byteArrayToHexString( printArray ));
		
		ResizableByteBuffer outputDecrypted = new ResizableByteBuffer(false, 5024, 5024, 0);
		encrypter.decrypt(output.getBuffer(), outputDecrypted);
		outputDecrypted.getBuffer().flip();
		inputBuffer.flip();
		byte[] outputDecryptedArray = new byte[outputDecrypted.getBuffer().limit()];
		outputDecrypted.getBuffer().get(outputDecryptedArray);
		System.err.println("Decoded: "+ByteTools.byteArrayToHexString( outputDecryptedArray ));
		assertArrayEquals( inputBuffer.array() ,  outputDecryptedArray);
	}

}
